package wili.sql;

import java.io.File;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import wili.c.Ca;
import wili.c.File9a;

/**
 * @author weila 2022年7月23日
 */
public class Tab {
	public String name;

	List<String> colNames = new ArrayList<>();

	Map<String, Col> colMap = new HashMap<>();

	SqlCont0 cont;

	public String toString() {
		List<Col> cc = new ArrayList<>(colMap.values());
		return cc.toString();
	}

	public Tab(String name, SqlCont0 cont) {
		this.cont = cont;
		this.name = name;
		String sql;
		String catalog = "SBODEMOUS.";
		switch (cont.dbType) {
		case "mysql":
			sql = "select * from " + name + " limit 1";
			break;
		default:
			sql = "select top 1 * from " + catalog + name;
			break;
		}
		ResultSet rs = cont.query(sql);
		int len;
		try {
			Ca.pause();
			ResultSetMetaData meta = rs.getMetaData();
			len = meta.getColumnCount();
			colNames = new ArrayList<>(len);
			for (int i = 0; i < len; i++) {
				String nam = meta.getColumnName(i + 1);
				colNames.add(nam);
				//String typ = meta.getColumnTypeName(i);
				colMap.put(nam, new Col(nam, this));
			}
			Collections.sort(colNames);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	static int inc;

	static File dir = new File("C:\\Perforce\\1810399\\BUSMB_B1\\SBO\\dev\\Source\\WebClient\\java\\t\\tableList");

	public void print() {
		if ("asdf".isEmpty()) {//cost much.
			this.getPrimaryKeys();
			this.getExportedKeys();
		}
		this.getImportedKeys();
		if (eKeys != null && eKeys.size() > 0)
			Ca.pause();
		StringBuilder sb = new StringBuilder();
		++inc;
		String headSt = "\n" + inc + "===================";
		sb.append(headSt + this.name + ":" + colNames.size());
		int ind = 0;
		if (pKeys != null) {
			for (int i = 0; i < pKeys.size(); i++) {
				++ind;
				Col col = pKeys.get(i);
				sb.append("\n " + ind + ", " + col.toString());
			}
		}
		for (int i = 0; i < colNames.size(); i++) {
			String cname = colNames.get(i);
			Col col = colMap.get(cname);
			if (pKeys != null && pKeys.contains(col))
				continue;
			++ind;
			sb.append("\n " + ind + ", " + col.toString());
		}
		sb.append(headSt + this.name + ":end.");
		if ("asdf".isEmpty())
			Ca.log(sb.toString());
		File9a.str2file(sb.toString(), new File(dir, this.name + ".txt"), -1);
	}

	List<Col> pKeys, eKeys, iKeys;

	public List<Col> getPrimaryKeys() {
		if (pKeys != null)
			return pKeys;
		DatabaseMetaData meta = cont.getDatabaseMetaData();
		try {
			List<Col> ret = new ArrayList<>(3);
			ResultSet res = meta.getPrimaryKeys(cont.catalog, cont.schema, name);
			while (res.next()) {
				String pname = res.getString("PK_NAME");
				String cname = res.getString("COLUMN_NAME");
				Col co = colMap.get(cname);
				if (co == null) {
					co = new Col(cname, this);
				}
				ret.add(co);
			}
			return this.pKeys = ret;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public Col getCol(String cname) {
		Col ret = colMap.get(cname);
		return ret;
	}

	/**
	 * 查找本表所引用的主键列
	 * 
	 * @return
	 */
	public List<Col> getImportedKeys() {
		if (iKeys != null)
			return iKeys;
		DatabaseMetaData meta = cont.getDatabaseMetaData();
		try {
			List<Col> ret = new ArrayList<>(3);
			ResultSet res = meta.getImportedKeys(cont.catalog, cont.schema, this.name);
			//ResultSet res = meta.getImportedKeys(null, null, name);
			while (res.next()) {
				String pkTable = res.getString("PKTABLE_NAME");
				String pkCol = res.getString("PKCOLUMN_NAME");
				String fkTable = res.getString("PKTABLE_NAME");
				String fkCol = res.getString("FKCOLUMN_NAME");
				Col fkCol2 = getCol(fkCol);
				Tab pkTable2 = cont.getTable(pkTable);
				Col pkCol2 = pkTable2.getCol(pkCol);
				pkCol2.setIsPrimKey();
				fkCol2.setPrimaryColumn(pkCol2);
				ret.add(pkCol2);//
			}
			return iKeys = ret;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 查找引用本表的外键列。
	 *
	 * @return
	 */
	public List<Col> getExportedKeys() {
		if (eKeys != null)
			return eKeys;
		DatabaseMetaData meta = cont.getDatabaseMetaData();
		try {
			List<Col> ret = new ArrayList<>(3);
			//ResultSet res = meta.getExportedKeys(cont.catalog, cont.schema, name);
			ResultSet res = meta.getExportedKeys(null, null, this.name);
			while (res.next()) {
				String pkTable = res.getString("PKTABLE_NAME");
				String pkCol = res.getString("PKCOLUMN_NAME");
				String fkTable = res.getString("PKTABLE_NAME");
				String fkCol = res.getString("FKCOLUMN_NAME");
				Col fkCol2 = getCol(fkCol);
				Tab pkTable2 = cont.getTable(pkTable);
				Col pkCol2 = pkTable2.getCol(pkCol);
				pkCol2.setIsPrimKey();
				fkCol2.setPrimaryColumn(pkCol2);
				ret.add(fkCol2);//引用本表的外键列可能有很多。
			}
			return eKeys = ret;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
}
